/*
 *  Copyright (c) 2013 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.yuntongxun.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
package com.yuntongxun.ecdemo.ui;

import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.utils.DateUtil;
import com.yuntongxun.ecdemo.common.utils.DemoUtils;
import com.yuntongxun.ecdemo.common.utils.ECPreferenceSettings;
import com.yuntongxun.ecdemo.common.utils.ECPreferences;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.common.utils.ResourceHelper;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.storage.ConversationSqlManager;
import com.yuntongxun.ecdemo.storage.GroupMemberSqlManager;
import com.yuntongxun.ecdemo.storage.GroupNoticeSqlManager;
import com.yuntongxun.ecdemo.ui.chatting.base.EmojiconTextView;
import com.yuntongxun.ecdemo.ui.chatting.model.Conversation;
import com.yuntongxun.ecdemo.ui.contact.ContactLogic;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;
import com.yuntongxun.ecdemo.ui.group.GroupNoticeHelper;
import com.yuntongxun.ecdemo.voicechat.bean.UserInfo;
import com.yuntongxun.ecdemo.voicechat.ui.services.DiscussionService;
import com.yuntongxun.ecdemo.voicechat.util.JsonHelper;
import com.yuntongxun.ecdemo.voicechat.view.MyImageSpan;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.ECMessage;
import com.yuntongxun.ecsdk.ECUserState;
import com.yuntongxun.ecsdk.SdkErrorCode;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;


/**
 * @author 容联•云通讯
 * @date 2014-12-8
 * @version 4.0
 */
public class ConversationAdapter extends CCPListAdapter <Conversation> {

    private OnListAdapterCallBackListener mCallBackListener;
    int padding;
    private ColorStateList[] colorStateLists ;
    private String isAtSession ;
    private  Context context;
    //MyImageSpan flagSpan;
    //MyImageSpan genderSpan;
    Bitmap manBitmap;
    Bitmap womanBitmap;

    /**
     * @param ctx
     */
    public ConversationAdapter(Context ctx , OnListAdapterCallBackListener listener) {
        super(ctx, new Conversation());
        context =ctx;
        mCallBackListener = listener;
        padding = ctx.getResources().getDimensionPixelSize(R.dimen.OneDPPadding);
        colorStateLists = new ColorStateList[]{
                ResourceHelper.getColorStateList(ctx, R.color.normal_text_color),
                ResourceHelper.getColorStateList(ctx, R.color.ccp_list_textcolor_three)
        };

        try {
            InputStream manStream = mContext.getAssets().open("ic_man.png");
            InputStream womanStream = mContext.getAssets().open("ic_woman.png");

            manBitmap = BitmapFactory.decodeStream(manStream);
            womanBitmap = BitmapFactory.decodeStream(womanStream);
        }
        catch (IOException e) {
            Log.e("----",e.toString());
        }
    }


    @Override
    protected Conversation getItem(Conversation t, Cursor cursor) {
        Conversation conversation = new Conversation();
        conversation.setCursor(cursor);
        if(conversation.getUsername() != null && conversation.getUsername().endsWith("@priategroup.com")) {
            ArrayList<String> member = GroupMemberSqlManager.getGroupMemberID(conversation.getSessionId());
            if(member != null) {
                ArrayList<String> contactName = ContactSqlManager.getContactName(member.toArray(new String[]{}));
                if(contactName != null && !contactName.isEmpty()) {
                    String chatroomName = DemoUtils.listToString(contactName, ",");
                    conversation.setUsername(chatroomName);
                }
            }
        }
        return conversation;
    }

    /**
     * 会话时间
     * @param conversation
     * @return
     */
    protected final CharSequence getConversationTime(Conversation conversation) {
        if(conversation.getSendStatus() == ECMessage.MessageStatus.SENDING.ordinal()) {
            return mContext.getString(R.string.conv_msg_sending);
        }
        if(conversation.getDateTime() <= 0) {
            return "";
        }
        return DateUtil.getDateString(conversation.getDateTime(),
                DateUtil.SHOW_TYPE_CALL_LOG).trim();
    }

    /**
     * 根据消息类型返回相应的主题描述
     * @param conversation
     * @return
     */
    protected final CharSequence getConversationSnippet(Conversation conversation) {
        if(conversation == null) {
            return "";
        }
        if(GroupNoticeSqlManager.CONTACT_ID.equals(conversation.getSessionId())) {
            return GroupNoticeHelper.getNoticeContent(conversation.getContent());
        }

        String fromNickName = "";
        if (conversation.getSessionId().toUpperCase().startsWith("G")) {
            if(conversation.getContactId() != null && CCPAppManager.getClientUser() != null
                    && !conversation.getContactId().equals(CCPAppManager.getClientUser().getUserId())) {
                ECContacts contact = ContactSqlManager.getContact(conversation.getContactId());
                if (contact != null && contact.getNickname() != null) {
                    fromNickName = contact.getNickname() + ": ";
                } else {
                    fromNickName = conversation.getContactId() + ": ";

                }
            }
        }

        // Android Demo 免打扰后需要显示未读条数
        if (!conversation.isNotice() && conversation.getUnreadCount() > 1) {
            fromNickName = "["+conversation.getUnreadCount()+"条]" + fromNickName;
        }


        if (conversation.getMsgType() == ECMessage.Type.VOICE.ordinal()) {
            return fromNickName + mContext.getString(R.string.app_voice);
        } else if(conversation.getMsgType() == ECMessage.Type.FILE.ordinal()) {
            return fromNickName + mContext.getString(R.string.app_file);
        } else if(conversation.getMsgType() == ECMessage.Type.IMAGE.ordinal()) {
            return fromNickName + mContext.getString(R.string.app_pic);
        } else if(conversation.getMsgType() == ECMessage.Type.VIDEO.ordinal()) {
            return fromNickName + mContext.getString(R.string.app_video);
        }else if(conversation.getMsgType()==ECMessage.Type.LOCATION.ordinal()){
            return fromNickName + mContext.getString(R.string.app_location);

        }
        String snippet = fromNickName + conversation.getContent();
        if(conversation.getSessionId().equals(isAtSession)) {
            return Html.fromHtml(mContext.getString(R.string.conversation_at, snippet));
        }
        return snippet;
    }

    /**
     * 根据消息发送状态处理
     * @param context
     * @param conversation
     * @return
     */
    public static Drawable getChattingSnippentCompoundDrawables(Context context ,Conversation conversation) {
        if(conversation.getSendStatus() == ECMessage.MessageStatus.FAILED.ordinal()) {
            return DemoUtils.getDrawables(context, R.drawable.msg_state_failed);
        } else if (conversation.getSendStatus() == ECMessage.MessageStatus.SENDING.ordinal()) {
            return DemoUtils.getDrawables(context, R.drawable.msg_state_sending);
        } else {
            return null;
        }
    }

    public UserInfo parseResult(String result) {
        JsonHelper<UserInfo> dataParser = new JsonHelper<UserInfo>(
                UserInfo.class);
        return dataParser.getData(
                result, "result");
    }

//    private List<String> ids;
//
//    public void setState(List<String> ids){
//        this.ids=ids;
//    }
//
//    public List<String> getState(){
//        return ids;
//    }

    private List<UserInfo> userInfos;

    public List<UserInfo> getUserInfos() {
        return userInfos;
    }

    public void setUserInfos(List<UserInfo> userInfos) {
        this.userInfos = userInfos;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View view;
        ViewHolder mViewHolder;
        if(convertView == null || convertView.getTag() == null) {
            view = View.inflate(mContext , R.layout.conversation_item, null);

            mViewHolder = new ViewHolder();
            //mViewHolder.user_avatar = (ImageView) view.findViewById(R.id.avatar_iv);
            //mViewHolder.prospect_iv = (ImageView) view.findViewById(R.id.avatar_prospect_iv);
            //mViewHolder.nickname_tv = (EmojiconTextView) view.findViewById(R.id.nickname_tv);
            mViewHolder.tipcnt_tv = (TextView) view.findViewById(R.id.tipcnt_tv);
            mViewHolder.update_time_tv = (TextView) view.findViewById(R.id.update_time_tv);
            mViewHolder.last_msg_tv = (EmojiconTextView) view.findViewById(R.id.last_msg_tv);
            //mViewHolder.image_input_text = (ImageView) view.findViewById(R.id.image_input_text);
            //mViewHolder.image_mute = (ImageView) view.findViewById(R.id.image_mute);

            //mViewHolder.infoTv=(TextView)view.findViewById(R.id.conversation_info);
            mViewHolder.statusImg=(ImageView)view.findViewById(R.id.user_status);

            mViewHolder.nameView = (TextView) view.findViewById(R.id.name);
            mViewHolder.ageView = (TextView) view.findViewById(R.id.age);
            mViewHolder.flagView = (ImageView) view.findViewById(R.id.flag_img);
            mViewHolder.genderView = (ImageView) view.findViewById(R.id.gender_img);
            //mViewHolder.languagesView = (TextView) view.findViewById(R.id.languages);

            view.setTag(mViewHolder);
        } else {
            view = convertView;
            mViewHolder = (ViewHolder) view.getTag();
        }

        Conversation conversation = getItem(position);
        if(conversation != null) {
//            String[] id={conversation.getSessionId()};
            if (getUserInfos()!=null){
                for (int i=0;i<getUserInfos().size();i++){
                    if(conversation.getSessionId().equals(getUserInfos().get(i).getId())){
                        conversation.setState(getUserInfos().get(i).getOnLine());
                        break;
                    }
                }
            }

            if(TextUtils.isEmpty(conversation.getUsername())) {
                mViewHolder.statusImg.setVisibility(View.VISIBLE);
                mViewHolder.nameView.setText(conversation.getSessionId());
                //mViewHolder.infoTv.setText(conversation.getSessionId());

                mViewHolder.ageView.setVisibility(View.INVISIBLE);
                mViewHolder.genderView.setVisibility(View.INVISIBLE);
                mViewHolder.flagView.setVisibility((view.INVISIBLE));
            } else {

                mViewHolder.ageView.setVisibility(View.VISIBLE);
                mViewHolder.statusImg.setVisibility(View.VISIBLE);
//                Log.e("name",conversation.getUsername());
                mViewHolder.nameView.setText(conversation.getUsername());
//                mViewHolder.infoTv.setText(conversation.getUsername());
                String info=conversation.getUsername();
//                Log.e("info",info);
                if (info.contains("(")){
                    int index=info.indexOf("(");
                    String message=info.substring(index+1,info.length()-1);
//                    String[] infos=message.split("-");
                    UserInfo infos=null;
                    try {
                        infos=parseResult(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


//                Log.e("size",infos.length+"");


                    if (infos!=null){
                        //mViewHolder.infoTv.setText(infos.getNickName());
                        String name = infos.getNickName();
                        String age = infos.getAge();
//
                        if (infos.getGender().equals("男"))
                        {
                            mViewHolder.genderView.setImageBitmap(manBitmap);
                        }
                        else
                        {
                            mViewHolder.genderView.setImageBitmap(womanBitmap);
                        }

                        //MyImageSpan nativeSpan = new MyImageSpan(mContext, R.drawable.ic_speak);
                        //MyImageSpan learnSpan = new MyImageSpan(mContext, R.drawable.ic_learn);

                        try {
                            InputStream is = mContext.getAssets().open("flag/"+infos.getCountry()+".png");
                            Bitmap bitmap = BitmapFactory.decodeStream(is);
                            mViewHolder.flagView.setImageBitmap(bitmap);
                            is.close();
                        } catch (IOException e) {
                            Log.e("----",e.toString());
                        }

                        //mViewHolder.infoTv.setText("");


                        mViewHolder.nameView.setText(name);


                        //插入性别图标
                        //SpannableString showString = new SpannableString("1");
                        //showString.setSpan(genderSpan,0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        //mViewHolder.infoTv.append(showString);

                        mViewHolder.ageView.setText(age);

                        //插入国旗图标
                        //showString.setSpan(flagSpan, 0, 1 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        //mViewHolder.infoTv.append(showString);

                        //mViewHolder.infoTv.append("  ");

                        //插入本地语言的图标
                        //showString.setSpan(nativeSpan, 0, 1 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        //mViewHolder.infoTv.append(showString);

                        //本地语言颜色
                        //SpannableString nativeShow = new SpannableString(nativel);
                        //ForegroundColorSpan greenSpan = new ForegroundColorSpan(mContext.getResources().getColor(R.color.voice_green));
                        //nativeShow.setSpan(greenSpan,0,native.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        //mViewHolder.infoTv.append(nativeShow);

                        //插入学习的图标
                        //showString.setSpan(learnSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        //mViewHolder.infoTv.append(showString);

                        //学习语言颜色
                        //SpannableString learnShow = new SpannableString(learn);
                        //ForegroundColorSpan greenSpan1 = new ForegroundColorSpan(mContext.getResources().getColor(R.color.voice_green));
                        //learnShow.setSpan(greenSpan1,0,learn.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        //mViewHolder.infoTv.append(learnShow);


                    }
                }else{
                    //mViewHolder.infoTv.setText(info);
                }
            }

            //handleDisplayNameTextColor(mViewHolder.nameView , conversation.getSessionId());
            mViewHolder.last_msg_tv.setText(getConversationSnippet(conversation));
            mViewHolder.last_msg_tv.setCompoundDrawables(getChattingSnippentCompoundDrawables(mContext, conversation), null, null, null);
            // 未读提醒设置
            setConversationUnread(mViewHolder, conversation);
            //mViewHolder.image_input_text.setVisibility(View.GONE);
            mViewHolder.update_time_tv.setText(getConversationTime(conversation));
            if(conversation.getSessionId().toUpperCase().startsWith("G")) {
                mViewHolder.statusImg.setVisibility(View.GONE);
                mViewHolder.ageView.setVisibility(View.INVISIBLE);
                mViewHolder.genderView.setVisibility(View.INVISIBLE);
                mViewHolder.flagView.setVisibility(View.INVISIBLE);
                mViewHolder.last_msg_tv.setVisibility(View.GONE);
                mViewHolder.update_time_tv.setVisibility(View.GONE);
            } else {
                mViewHolder.statusImg.setVisibility(View.VISIBLE);
                mViewHolder.statusImg.setVisibility(View.VISIBLE);
                mViewHolder.ageView.setVisibility(View.VISIBLE);
                mViewHolder.genderView.setVisibility(View.VISIBLE);
                mViewHolder.flagView.setVisibility(View.VISIBLE);
                mViewHolder.last_msg_tv.setVisibility(View.VISIBLE);
                mViewHolder.update_time_tv.setVisibility(View.VISIBLE);
            }
            //mViewHolder.image_mute.setVisibility(isNotice(conversation)? View.GONE :View.VISIBLE);

            if (conversation.getState().equals(UserInfo.ONLINE)){
                mViewHolder.statusImg.setImageResource(R.drawable.ic_green_bg);
            }else if (conversation.getState().equals(UserInfo.BUSY)){
                mViewHolder.statusImg.setImageResource(R.drawable.ic_busy);
            }else{
                mViewHolder.statusImg.setImageResource(R.drawable.ic_offline);
            }

        }

        boolean isTop = ConversationSqlManager.querySessionisTopBySessionId(conversation.getSessionId());
        if(isTop&&!conversation.getSessionId().equals(GroupNoticeSqlManager.CONTACT_ID)){
            view.setBackgroundColor(mContext.getResources().getColor(R.color.list_bg_gaoliang));
        }else {
            view.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.list_item_selector));

        }


        if(mViewHolder.nameView.getText().toString().trim().startsWith("gg")&&mViewHolder.nameView.getText().toString().trim().length()>=12){
            Log.e("--","--");
            mContext.startService(new Intent(mContext,DiscussionService.class));
        }

        return view;
    }

//    private void async(String[] ids,final ViewHolder mViewHolder) {
//
//        if (ids.length <= 0) {
//            return;
//        }

//        ECDevice.getUsersState(ids, new ECDevice.OnGetUsersStateListener() {
//            @Override
//            public void onGetUsersState(ECError ecError, ECUserState... ecUserStates) {
//                if (ecError.errorCode == SdkErrorCode.REQUEST_SUCCESS && ecUserStates != null) {
//                    for (int i = 0; i < ecUserStates.length; i++) {
//                        ECUserState userState = ecUserStates[i];
//                        for (int j = 0; j < getCount(); j++) {
//
//                            if (userState.getUserId().equals(getItem(j).getSessionId())) {
////                                getItem(j).setState(userState.isOnline() ? 0 : 1);
//                                if (userState.isOnline() ){
//                                    mViewHolder.statusImg.setImageResource(R.drawable.ic_green_bg);
//                                }else{
//                                    mViewHolder.statusImg.setImageResource(R.drawable.ic_busy);
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        });
//    }



    private void handleDisplayNameTextColor(EmojiconTextView textView, String contactId) {
        if(ContactLogic.isCustomService(contactId)) {
            textView.setTextColor(colorStateLists[1]);
        } else {
            textView.setTextColor(colorStateLists[0]);
        }
    }

    /**
     * 设置未读图片显示规则
     * @param mViewHolder
     * @param conversation
     */
    private void setConversationUnread(ViewHolder mViewHolder, Conversation conversation) {
        String msgCount = conversation.getUnreadCount() > 100 ? "..." : String.valueOf(conversation.getUnreadCount());
        mViewHolder.tipcnt_tv.setText(msgCount);
        if(conversation.getUnreadCount() == 0) {
            mViewHolder.tipcnt_tv.setVisibility(View.GONE);
            //mViewHolder.prospect_iv.setVisibility(View.GONE);
        } else if (conversation.isNotice()) {
            mViewHolder.tipcnt_tv.setVisibility(View.VISIBLE);
            //mViewHolder.prospect_iv.setVisibility(View.GONE);
        } else {
            //mViewHolder.prospect_iv.setVisibility(View.VISIBLE);
            mViewHolder.tipcnt_tv.setVisibility(View.GONE);
        }
    }

    static class ViewHolder {
        //ImageView user_avatar;
        TextView tipcnt_tv;
        //ImageView prospect_iv;
        //EmojiconTextView nickname_tv;
        TextView update_time_tv;
        EmojiconTextView last_msg_tv;
        //ImageView image_input_text;
        //ImageView image_mute;

        //TextView infoTv;
        ImageView statusImg;

        @InjectView(R.id.name)
        TextView nameView;
        @InjectView(R.id.gender_img)
        ImageView genderView;
        @InjectView(R.id.age)
        TextView ageView;
        @InjectView(R.id.flag_img)
        ImageView flagView;
        //@InjectView(R.id.languages)
        //TextView languagesView;
    }

    @Override
    protected void initCursor() {
        notifyChange();
    }

    @Override
    protected void notifyChange() {
        if(mCallBackListener != null) {
            mCallBackListener.OnListAdapterCallBack();
        }
        Cursor cursor = ConversationSqlManager.getConversationCursor();

        setCursor(cursor);
        isAtSession = ECPreferences.getSharedPreferences().getString(ECPreferenceSettings.SETTINGS_AT.getId() , "");
        super.notifyDataSetChanged();
    }

    private boolean isNotice(Conversation conversation) {
        if(conversation.getSessionId().toLowerCase().startsWith("g")) {
            return conversation.isNotice();
        }
        return true;
    }

}
